package com.pureut.equipment.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.utils.DateUtils;
import com.pureut.common.core.web.domain.AjaxResult;
import com.pureut.common.datascope.annotation.DataScope;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.equipment.domain.*;
import com.pureut.equipment.domain.dto.DeviceRecordDto;
import com.pureut.equipment.domain.dto.EquipmentKnowledgeDto;
import com.pureut.equipment.domain.dto.EquipmentRepairDto;
import com.pureut.equipment.domain.dto.SysLineDto;
import com.pureut.equipment.domain.vo.EquipmentRepairVo;
import com.pureut.equipment.domain.vo.ReturnDeviceStatusVo;
import com.pureut.equipment.mapper.DeviceRecordMapper;
import com.pureut.equipment.mapper.EquipmentKnowledgeMapper;
import com.pureut.equipment.mapper.EquipmentRepairMapper;
import com.pureut.equipment.service.DeviceRecordService;
import com.pureut.equipment.service.IEquipmentKnowledgeService;
import com.pureut.equipment.service.IEquipmentRepairService;
import com.pureut.system.api.FeignService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

/**
 * @Description 设备维修实现类
 * @Param EquipmentRepair
 * @Date 23-04-24f
 * @Author hl
 **/
@Service
public class EquipmentRepairServiceImpl extends ServiceImpl<EquipmentRepairMapper, EquipmentRepair> implements IEquipmentRepairService {

    @Resource
    private EquipmentRepairMapper equipmentRepairMapper;

    @Resource
    private FeignService feignService;

    @Resource
    private DeviceRecordMapper deviceRecordMapper;

    @Resource
    private DeviceRecordService deviceRecordService;

    @Resource
    EquipmentKnowledgeMapper equipmentKnowledgeMapper;

    @Resource
    IEquipmentKnowledgeService equipmentKnowledgeService;

    /**
     * 查询设备维修列表
     *
     * @param equipmentRepairVo 接受类
     * @return 设备维修列表
     */
    @Override
    @DataScope(deptAlias = "t1")
    public List<EquipmentRepairDto> selectRepairList(EquipmentRepairVo equipmentRepairVo) {
        return equipmentRepairMapper.selectRepairList(equipmentRepairVo);
    }

    /**
     * 新增设备维修
     *
     * @param equipmentRepair 接受类
     * @return 成功 true 失败 false
     */
    @Override
    public boolean insertEquipmentRepair(EquipmentRepair equipmentRepair) {
        String authorityCoding = feignService.getAuthorityCoding("device:repair:list");
        if (authorityCoding == null) {
            throw new GlobalException("该单据未进行配置，无法生成单据编码");
        }
        equipmentRepair.setRepairCode(authorityCoding);
        equipmentRepair.setCreateTime(DateUtils.getTime());
        equipmentRepair.setDeptId(String.valueOf(SecurityUtils.getDeptId()));
        equipmentRepair.setRepairState("1");
        equipmentRepair.setRepairWarrantyTime(DateUtils.getTime());
        return save(equipmentRepair);
    }

    /**
     * 修改设备维修
     *
     * @param equipmentRepair 接受类
     * @return 成功 true 失败 false
     */
    @Override
    public boolean updateEquipmentRepair(EquipmentRepair equipmentRepair) {
        return updateById(equipmentRepair);
    }

    /**
     * 查询单个设备维修列表
     *
     * @param repairId id
     * @return 设备维修列表
     */
    @Override
    public EquipmentRepairDto selectRepairById(long repairId) {
        EquipmentRepairDto equipmentRepairDto = equipmentRepairMapper.selectRepairById(repairId);
        String lineCode = equipmentRepairDto.getInstallationLocation();
        AjaxResult modelingLineInfo = feignService.getModelingLineInfo(lineCode);
        SysLineDto sysLineDto = JSON.parseObject(JSON.toJSONString(modelingLineInfo.get("data")), SysLineDto.class);
        equipmentRepairDto.setInstallationLocationName(sysLineDto.getLineName());
        return equipmentRepairDto;
    }

    /**
     * 删除设备维修
     *
     * @param repairId id
     * @return 成功 true 失败 false
     */
    @Override
    public boolean deleteRepairById(long repairId) {
        return removeById(repairId);
    }

    /**
     * 派工
     *
     * @param equipmentDispatch
     * @return 成功 1 失败 0
     */
    @Override
    public int dispatchEquipmentRepair(EquipmentDispatch equipmentDispatch) {
        equipmentDispatch.setRepairDispatchTime(DateUtils.getTime());
        String code = equipmentDispatch.getDeviceCode();
        long deviceId = deviceRecordMapper.selectEquipmentById(code);
        ReturnDeviceStatusVo returnDeviceStatusVo = new ReturnDeviceStatusVo();
        returnDeviceStatusVo.setDeviceIds(String.valueOf(deviceId));
        returnDeviceStatusVo.setStatus(3);
        deviceRecordService.returnDeviceStatus(returnDeviceStatusVo);
        return equipmentRepairMapper.dispatchEquipmentRepair(equipmentDispatch);
    }

    /**
     * 执行维修
     *
     * @param equipmentMaintenance
     * @return 成功 1 失败 0
     */
    @Override
    public int maintenanceEquipmentRepair(EquipmentMaintenance equipmentMaintenance) {
        long endTime = equipmentMaintenance.getRepairEndTime().getTime();
        long startTime = equipmentMaintenance.getRepairStartTime().getTime();
        long diff = (endTime - startTime) / 1000 / 60;
        BigDecimal bd = new BigDecimal(diff);
        BigDecimal bd2 = new BigDecimal(60);
        bd = bd.divide(bd2, RoundingMode.CEILING);
        equipmentMaintenance.setRepairTime(bd.doubleValue());
        return equipmentRepairMapper.maintenanceEquipmentRepair(equipmentMaintenance);
    }

    /**
     * 提交审核
     *
     * @param repairId id
     * @return 成功 1 失败 0
     */
    @Override
    public int submitEquipmentRepair(long repairId) {
        EquipmentState equipmentState = new EquipmentState();
        equipmentState.setRepairState(4);
        equipmentState.setRepairId(repairId);
        return equipmentRepairMapper.submitEquipmentRepair(equipmentState);
    }

    /**
     * 审核单据
     *
     * @param equipmentState id
     * @return 成功 1 失败 0
     */
    @Override
    public int auditEquipmentRepair(EquipmentState equipmentState) {
        Long userId = SecurityUtils.getUserId();
        AjaxResult sequence = feignService.getSequenceTwo("equipment:repair:audit", 7, equipmentState.getRepairWhether(), equipmentState.getRepairOpinion(), equipmentState.getRepairCode(), userId);
        Integer data = JSON.parseObject(JSON.toJSONString(sequence.get("data")), Integer.class);
        if (data == null) {
            throw new GlobalException("未对该审核进行配置");
        }
        int state = 0;
        switch (data) {
            case 1:
                equipmentState.setRepairState(7);
                break;
            case 2:
                equipmentState.setRepairState(5);
                break;
            case 3:
                throw new GlobalException("该用户无权限进行审核");
            case 4:
                throw new GlobalException("该用户已审核过");
        }
        //1 审核完成、2 还存在下个审核、3 没权限 、4 该人员已审核
        return equipmentRepairMapper.submitEquipmentRepair(equipmentState);
    }


    /**
     * 添加知识库
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addKnowLedge(Long id) {
        //获取设备维修信息
        EquipmentRepair equipmentRepair = getById(id);
        //只能对已完成的单据进行添加知识库功能
        if (!"7".equals(equipmentRepair.getRepairState())) {
            throw new GlobalException("只能对已完成的单据进行添加知识库功能");
        }
        //添加了的维修单不可重复添加知识库，若重复操作则提示“此单据已记录在知识库中"
        EquipmentKnowledgeDto equipmentKnowledgeDto = equipmentKnowledgeMapper.selectKnowledgeByCode(equipmentRepair.getRepairCode());
        if (equipmentKnowledgeDto != null) {
            throw new GlobalException("此单据已记录在知识库中");
        }
        //生成一条数据。同步数据：设备信息、故障类型、故障描述、故障图片、故障分析、处理过程、备件信息、知识库名称默认为"设备名称"+“知识库”）
        EquipmentKnowledge equipmentKnowledge = new EquipmentKnowledge();
        //获取设备信息
        long l = Long.parseLong(equipmentRepair.getDeviceId());
        DeviceRecord byId = deviceRecordService.getById(l);
        String authorityCoding = feignService.getAuthorityCoding("device:knowledge:list");
        equipmentKnowledge.setKnowledgeCode(authorityCoding)
                .setKnowledgeName(byId.getDeviceName() + "知识库")
                .setDeviceId(l)
                .setKnowledgeFailureType(Integer.parseInt(equipmentRepair.getRepairFailureType()))
                .setKnowledgeFailureDescription(equipmentRepair.getRepairFailureDescription())
                .setKnowledgeFailurePicture(equipmentRepair.getRepairFailurePicture())
                .setKnowledgeFailureAnalysis(equipmentRepair.getRepairAnalysis())
                .setKnowledgeFailureProcess(equipmentRepair.getRepairDealWith())
                .setCreateTime(DateUtils.getTime())
                .setCreateBy(SecurityUtils.getUsername())
                .setDeptId(String.valueOf(SecurityUtils.getDeptId()))
                .setRepairCode(equipmentRepair.getRepairCode());

        return equipmentKnowledgeMapper.saveData(equipmentKnowledge) > 0;
    }
}
